from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db

import os

from util import *

class WineEntry(db.Model):
    name = db.StringProperty()
    year = db.IntegerProperty()
    dateEntered = db.DateTimeProperty(auto_now_add=True)
    description = db.TextProperty()
    wineType = db.StringProperty()
    row = db.IntegerProperty()
    column = db.IntegerProperty()

class WineCollection:
    def __init__(self, nRow, nColumns):
        self.rows = [WineRow(i, nColumns) for i in range(nRow)]

class NoWine:
    def __init__(self, row, column):
        self.row = row
        self.column = column

class WineRow:
    def __init__(self, rowNumber, numberOfColumns):
        self.id = ""
        self.rowNumber = rowNumber
        self.wines = [NoWine(rowNumber, i) for i in range(numberOfColumns)]

class ShowWineCellar(webapp.RequestHandler):
    def get(self):

        pagePath = []
        pagePath.append(PageDir("vink&aelig;lder", ""))

        # Create collection
        wineCollection = WineCollection(5, 7)

        # Set ids
        i = 0
        for id in ("A", "B", "C", "D", "E"):
            wineCollection.rows[i].id = id
            i = i + 1

        # Load wines from database
        wines = db.GqlQuery("SELECT * FROM WineEntry")
        for wine in wines:
            if wine.name:
                wineCollection.rows[wine.row].wines[wine.column] = wine
            else:
                wine.delete()

        wineList = db.GqlQuery("SELECT * FROM WineEntry ORDER BY name")

        template_values = {
            'path': pagePath,
            'wines': wineCollection,
            'wineList': wineList,
            'user': MyUser()
        }

        path = os.path.join(os.path.dirname(__file__), 'wineCellar.html')
        self.response.out.write(template.render(path, template_values))

def LoadWine(row, column):
    wines = db.GqlQuery("SELECT * FROM WineEntry WHERE row = :1 AND column = :2", row, column)
    return wines.get()

class ShowWine(webapp.RequestHandler):
    def get(self):
        myUser = MyUser()

        row = long(self.request.get('row'))
        column = long(self.request.get('column'))
        
        wine = LoadWine(row, column)
        if wine == None:
            self.redirect("/wineCellar")
            
        pagePath = []
        pagePath.append(PageDir("vink&aelig;lder", "wineCellar"))
        pagePath.append(PageDir("position [%i, %i]" % (wine.row, wine.column), ""))

        template_values = {
            'wine': wine,
            'path': pagePath,
            'user': MyUser(),
            'fgColor': "\"#FFFFFF\"",
        }
        path = os.path.join(os.path.dirname(__file__), 'showWine.html')
        self.response.out.write(template.render(path, template_values))

class EditWine(webapp.RequestHandler):
    def get(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/wineCellar")

        row = long(self.request.get('row'))
        column = long(self.request.get('column'))
        
        wine = LoadWine(row, column)
        if wine == None:
            wine = WineEntry()
            wine.name = ""
            wine.description = ""
            wine.row = row
            wine.column = column
            wine.year = 2011
            wine.put()
            
        pagePath = []
        pagePath.append(PageDir("vink&aelig;lder", "wineCellar"))
        pagePath.append(PageDir("position [%i, %i] : EDIT" % (wine.row, wine.column), ""))

        wineList = db.GqlQuery("SELECT * FROM WineEntry ORDER BY name")

        template_values = {
            'wine': wine,
            'path': pagePath,
            'user': MyUser(),
            'fgColor': "\"#FFFFFF\"",
            'wineList': wineList
        }
        path = os.path.join(os.path.dirname(__file__), 'editWine.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        myUser = MyUser()
        if not myUser.canEdit:
            self.redirect("/wineCellar")

        row = long(self.request.get('row'))
        column = long(self.request.get('column'))
        
        wine = LoadWine(row, column)
        if self.request.get('delete'):
            wine.delete()
        else:            
            wine.name = self.request.get('name').strip()
            wine.year = long(self.request.get('year').strip())
            wine.wineType = self.request.get('type').strip()
            wine.put()
        
        self.redirect("/wineCellar")
